package com.zifeng.canal;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.zifeng.pojo.User;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CanalMessageToObject {

    public static User convertToUser(List<CanalEntry.Column> columns) {
        Map<String, String> fieldMap = new HashMap<>();
        for (CanalEntry.Column column : columns) {
            // 将 column name（如 login_username）转成 loginUsername 再放入 map
            String fieldName = underlineToCamel(column.getName());
            fieldMap.put(fieldName, column.getValue());
        }

        User user = new User();
        try {
            Field[] fields = User.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String value = fieldMap.get(field.getName());
                if (value != null) {
                    Object convertedValue = convertValue(value, field.getType());
                    field.set(user, convertedValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }


    public static <T> T convertTo(Class<T> clazz, List<CanalEntry.Column> columns) {
        Map<String, String> fieldMap = new HashMap<>();
        for (CanalEntry.Column column : columns) {
            String fieldName = underlineToCamel(column.getName());
            fieldMap.put(fieldName, column.getValue());
        }

        try {
            T instance = clazz.getDeclaredConstructor().newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String rawValue = fieldMap.get(field.getName());
                if (rawValue != null) {
                    Object value = convertValue(rawValue, field.getType());
                    field.set(instance, value);
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException("Canal column to bean conversion failed", e);
        }
    }

    private static Object convertValue(String value, Class<?> targetType) throws ParseException {
        if (targetType == String.class) {
            return value;
        } else if (targetType == Integer.class || targetType == int.class) {
            return Integer.parseInt(value);
        } else if (targetType == Long.class || targetType == long.class) {
            return Long.parseLong(value);
        } else if (targetType == Double.class || targetType == double.class) {
            return Double.parseDouble(value);
        } else if (targetType == Float.class || targetType == float.class) {
            return Float.parseFloat(value);
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return Boolean.parseBoolean(value);
        } else if (targetType == Date.class) {
            // 自动判断格式 yyyy-MM-dd / yyyy-MM-dd HH:mm:ss
            if (value.length() == 10) {
                return new SimpleDateFormat("yyyy-MM-dd").parse(value);
            } else {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
            }
        }
        return null;
    }



    private static String underlineToCamel(String underline) {
        StringBuilder result = new StringBuilder();
        boolean toUpper = false;
        for (int i = 0; i < underline.length(); i++) {
            char c = underline.charAt(i);
            if (c == '_') {
                toUpper = true;
            } else {
                result.append(toUpper ? Character.toUpperCase(c) : c);
                toUpper = false;
            }
        }
        return result.toString();
    }

//    public static User convertToUser(List<CanalEntry.Column> columns) {
//        Map<String, String> fieldMap = new HashMap<>();
//        for (CanalEntry.Column column : columns) {
//            // 将 column name（如 login_username）转成 loginUsername 再放入 map
//            String fieldName = underlineToCamel(column.getName());
//            fieldMap.put(fieldName, column.getValue());
//        }
//        User user = new User();
//        try {
//            Field[] fields = User.class.getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                String value = fieldMap.get(field.getName());
//                if (value != null) {
//                    Object convertedValue = convertValue(value, field.getType());
//                    field.set(user, convertedValue);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return user;
//    }
//
//    public static String underlineToCamel(String underline) {
//        StringBuilder result = new StringBuilder();
//        boolean toUpper = false;
//        for (int i = 0; i < underline.length(); i++) {
//            char c = underline.charAt(i);
//            if (c == '_') {
//                toUpper = true;
//            } else {
//                result.append(toUpper ? Character.toUpperCase(c) : c);
//                toUpper = false;
//            }
//        }
//        return result.toString();
//    }
//
//    private static Object convertValue(String value, Class<?> targetType) {
//        if (targetType == String.class) {
//            return value;
//        } else if (targetType == Long.class || targetType == long.class) {
//            return Long.parseLong(value);
//        } else if (targetType == Integer.class || targetType == int.class) {
//            return Integer.parseInt(value);
//        } else if (targetType == Date.class) {
//
//            try {
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                return sdf.parse(value);
//            } catch (ParseException e) {
//                throw new RuntimeException(e);
//            }
//
//        } else if (targetType == Boolean.class || targetType == boolean.class) {
//            return Boolean.parseBoolean(value);
//        }
//        // 可根据需要添加更多类型转换
//        return null;
//    }
}
